package com.jeesite.modules.config.web;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.shiro.realm.CasAuthorizingRealm;
import com.jeesite.common.shiro.session.SessionDAO;
import com.jeesite.common.shiro.web.WebSecurityManager;
import com.jeesite.modules.fl.web.weixin.WeixinRealm;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.apache.shiro.realm.Realm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.Collection;

@Configuration
@EnableConfigurationProperties(WeixinProperties.class)
public class WeixinConfig extends WebMvcConfigurerAdapter {
  private Logger log = LoggerFactory.getLogger(WeixinConfig.class);

  @Autowired
  private WeixinProperties weixinProperties;
  @Autowired(required = false)
  private WxMpService wxMpService;

  @Bean
  @ConditionalOnProperty(prefix = "weixin", name="enable", havingValue = "true")
  public WxMpService wxMpService() {
    if (StringUtils.isEmpty(weixinProperties.getAppId())) {
      return null;
    }
    WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
    configStorage.setAppId(weixinProperties.getAppId());
    configStorage.setSecret(weixinProperties.getSecret());
    configStorage.setToken(weixinProperties.getToken());
    configStorage.setAesKey(weixinProperties.getAesKey());

    WxMpService service = new WxMpServiceImpl();
    service.setWxMpConfigStorage(configStorage);
    return service;
  }



  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    super.addInterceptors(registry);
    if (Boolean.TRUE.equals(weixinProperties.getEnable())
        && wxMpService != null
    ) {
//      registry.addInterceptor(new WeixinUserInterceptor(wxMpService, weixinProperties));
    }
  }


  @Bean
  public WeixinRealm weixinRealm(
      SessionDAO sessionDAO, CasAuthorizingRealm casAuthorizingRealm,
      WebSecurityManager webSecurityManager) {
    log.debug("register new realm");
    WeixinRealm bean = new WeixinRealm();
    bean.setSessionDAO(sessionDAO);
    Collection<Realm> realms = ListUtils.newArrayList();
    realms.add(bean);
    realms.add(casAuthorizingRealm);
    webSecurityManager.setRealms(realms);
    return bean;
  }
}
